<template>
  <div class="address-container container">

    <el-skeleton :loading="loading" animated>
      <template #default>
        <el-table
            :data="addressList"
            style="width: 80%"
            stripe
            empty-text="暂无地址信息"
            v-if="addressList.length > 0"
        >
          <!-- 收货人列 -->
          <el-table-column label="收货人" width="120">
            <template #default="{ row }">
              <div class="receiver-cell">
                <span class="name">{{ row.name }}</span>
                <el-tag
                    v-if="row.defaultStatus === 1"
                    size="small"
                    type="danger"
                    class="default-tag"
                >
                  默认
                </el-tag>
              </div>
            </template>
          </el-table-column>

          <!-- 联系方式列 -->
          <el-table-column prop="phoneNumber" label="联系方式" width="130"/>

          <!-- 所在地区列 -->
          <el-table-column label="所在地区" min-width="150">
            <template #default="{ row }">
              <div class="region-cell">
                {{ row.province }} {{ row.city }} {{ row.region }}
              </div>
            </template>
          </el-table-column>

          <!-- 详细地址列 -->
          <el-table-column label="详细地址" min-width="200">
            <template #default="{ row }">
              <div class="address-cell">
                {{ row.detailAddress }}
                <div class="post-code" v-if="row.postCode">邮编：{{ row.postCode }}</div>
              </div>
            </template>
          </el-table-column>

          <!-- 操作列 -->
          <el-table-column label="操作" width="220" fixed="right">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button
                    size="small"
                    @click="handleEdit(row)"
                >
                  编辑
                </el-button>
                <el-button
                    size="small"
                    type="danger"
                    @click="handleDelete(row.id)"
                >
                  删除
                </el-button>
<!--                <el-button-->
<!--                    v-if="row.defaultStatus === 0"-->
<!--                    size="small"-->
<!--                    type="warning"-->
<!--                    @click="handleSetDefault(row.id)"-->
<!--                >-->
<!--                  设默认-->
<!--                </el-button>-->
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-empty v-else description="暂无地址信息"/>
      </template>
    </el-skeleton>
    <div class="footer-buttons">
      <el-button
          type="primary"
          @click="handleAdd"
          size="large"
          class="add-button"
      >
        新增地址
      </el-button>
    </div>
    <!-- 地址表单对话框 -->
    <el-dialog
        :title="formMode === 'add' ? '新增地址' : '编辑地址'"
        v-model="formVisible"
        width="600px"
    >
      <el-form :model="form" :rules="rules" label-width="80px">
        <el-form-item label="收货人" prop="name">
          <el-input v-model="form.name" placeholder="请输入收货人姓名"/>
        </el-form-item>

        <el-form-item label="联系方式" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" placeholder="请输入手机号码"/>
        </el-form-item>

        <!--        <el-form-item label="省市区" prop="selectedRegion">-->
        <!--          <el-cascader-->
        <!--              v-model="form.selectedRegion"-->
        <!--              :props="cascaderProps"-->
        <!--              :show-all-levels="false"-->
        <!--              placeholder="请选择省市区"-->
        <!--              style="width: 100%"-->
        <!--              clearable-->
        <!--          />-->
        <!--        </el-form-item>-->
        <el-form-item label="省份" prop="province">
          <el-input v-model="form.province" placeholder="请输入省份"/>
        </el-form-item>

        <el-form-item label="城市" prop="city">
          <el-input v-model="form.city" placeholder="请输入城市"/>
        </el-form-item>

        <el-form-item label="区县" prop="region">
          <el-input v-model="form.region" placeholder="请输入区县"/>
        </el-form-item>

        <el-form-item label="详细地址" prop="detailAddress">
          <el-input
              v-model="form.detailAddress"
              type="textarea"
              placeholder="请输入详细地址"
              :rows="3"
          />
        </el-form-item>

        <el-form-item label="邮政编码" prop="postCode">
          <el-input v-model="form.postCode" placeholder="请输入邮政编码"/>
        </el-form-item>

        <el-form-item label="默认地址">
          <el-switch
              v-model="form.defaultStatus"
              :active-value="1"
              :inactive-value="0"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="formVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {
  getAddressListAPI,
  updateAddressAPI,
  deleteAddressAPI,
  // setDefaultAddressAPI,
} from '@/apis/address'
import Cookies from "js-cookie";
import {addAddressAPI} from "@/apis/user";

const addressList = ref([])
const loading = ref(false)
const memberId = Cookies.get('memberId')
// const cascaderProps = null; // 删除级联配置
// 表单相关
const formVisible = ref(false)
const formMode = ref('add')

const form = ref({
  id: null,
  name: '',
  phoneNumber: '',
  province: '',
  city: '',
  region: '',
  detailAddress: '',
  postCode: '',
  defaultStatus: 0
});


// 表单验证规则
const rules = {
  name: [{required: true, message: '请输入收货人', trigger: 'blur'}],
  phoneNumber: [
    {required: true, message: '请输入联系方式', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur'}
  ],
  // 其他规则保持不变
  province: [{required: true, message: '请输入省份', trigger: 'blur'}],
  city: [{required: true, message: '请输入城市', trigger: 'blur'}],
  region: [{required: true, message: '请输入区县', trigger: 'blur'}],
  detailAddress: [{required: true, message: '请输入详细地址', trigger: 'blur'}]
}

// 获取地址列表
const getAddressList = async () => {
  try {
    loading.value = true
    const res = await getAddressListAPI(memberId)

    const addresses = await Promise.all(
        res.data.map(async item => ({
          ...item,
          province: item.province,
          city: item.city,
          region: item.region
        }))
    )
    addressList.value = addresses
  } finally {
    loading.value = false
  }
}

// 地区名称缓存
// const regionCache = ref(new Map())
// const getRegionName = async (code) => {
//   if (!code) return ''
//   if (regionCache.value.has(code)) return regionCache.value.get(code)
//
//   try {
//     console.log("code: "+code)
//     const res = await getRegionChildrenAPI(code)
//     console.log("res: "+res)
//     const region = res.data.find(item => item.code === code)
//     if (region) {
//       regionCache.value.set(code, region.name)
//       return region.name
//     }
//     return ''
//   } catch {
//     return ''
//   }
// }

// 处理新增地址
const handleAdd = () => {
  formMode.value = 'add'
  form.value = {
    id: null,
    name: '',
    phoneNumber: '',
    selectedRegion: [],
    detailAddress: '',
    postCode: '',
    defaultStatus: 0
  }
  formVisible.value = true
}

// 处理编辑地址
const handleEdit = (address) => {
  formMode.value = 'edit'
  form.value = {
    ...address,
    selectedRegion: address.selectedRegion || []
  }
  formVisible.value = true
}

// 提交表单
const submitForm = async () => {
  try {
    const params = {
      ...form.value,
      province: form.value.province,
      city: form.value.city,
      region: form.value.region,
      detailAddress: form.value.detailAddress,
      postCode: form.value.postCode,
      defaultStatus: form.value.defaultStatus,
      memberId:memberId
    }

    if (formMode.value === 'add') {
      await addAddressAPI(params)
      ElMessage.success('添加成功')
    } else {
      await updateAddressAPI(params)
      ElMessage.success('修改成功')
    }

    formVisible.value = false
    await getAddressList()
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '操作失败，请稍后重试')
  }
}

// 删除地址
const handleDelete = (id) => {
  ElMessageBox.confirm('确定要删除该地址吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    await deleteAddressAPI(id)
    ElMessage.success('删除成功')
    await getAddressList()
  })
}

// 设置默认地址
// const handleSetDefault = async (id) => {
//   await setDefaultAddressAPI(id)
//   ElMessage.success('设置默认成功')
//   await getAddressList()
// }

onMounted(() => {
  getAddressList()
})
</script>

<style scoped lang="scss">
/* 保持之前的样式不变，添加邮编样式 */
.address-cell {
  .post-code {
    color: #909399;
    font-size: 12px;
    margin-top: 4px;
  }
}

//.address-container {
//  padding: 24px;
//  background: #fff;
//  min-height: calc(100vh - 100px);
//  box-sizing: border-box;
//
//  .header {
//    display: flex;
//    justify-content: space-between;
//    align-items: center;
//    margin-bottom: 24px;
//    padding-bottom: 24px;
//    border-bottom: 1px solid #e4e7ed;
//
//    h2 {
//      margin: 0;
//      font-size: 20px;
//      color: #303133;
//      font-weight: 600;
//    }
//  }
//}

.address-container {
  // 添加底部padding防止按钮遮挡内容
  padding-bottom: 80px;
  position: relative;

  .footer-buttons {
    position: fixed;
    bottom: 20px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 1000;
    display: flex;
    justify-content: center;
    width: 100%;
    max-width: 1200px; // 根据实际布局调整
    background: linear-gradient(to top, rgba(255, 255, 255, 1) 80%, rgba(255, 255, 255, 0));

    .add-button {
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      padding: 16px 32px;
      font-size: 16px;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
      }
    }
  }
}
/* 优化表格样式 */
:deep(.el-table) {
  th.el-table__cell {
    background-color: #f8f9fa;
    font-weight: 600;
    color: #495057;
  }

  .el-table__row {
    transition: all 0.3s ease;

    &:hover {
      background-color: #f8f9fa !important;
      transform: translateY(-2px);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    }
  }

  .receiver-cell {
    display: flex;
    align-items: center;

    .name {
      margin-right: 8px;
      font-weight: 500;
    }

    .default-tag {
      height: 22px;
      line-height: 20px;
    }
  }

  .region-cell {
    color: #606266;
  }

  .address-cell {
    color: #909399;
    word-break: break-word;
    line-height: 1.5;
  }

  .action-buttons {
    display: flex;
    gap: 8px;

    .el-button {
      padding: 8px 12px;
      transition: transform 0.2s;

      &:hover {
        transform: scale(1.05);
      }
    }
  }
}

@media (max-width: 768px) {
  .address-container {
    padding: 16px;

    :deep(.el-table) {
      th, td {
        padding: 12px 8px;
      }

      .el-table__cell {
        .receiver-cell {
          flex-direction: column;
          align-items: flex-start;

          .default-tag {
            margin-top: 4px;
          }
        }

        .action-buttons {
          flex-wrap: wrap;
          gap: 4px;

          .el-button {
            padding: 6px 8px;
            font-size: 12px;
          }
        }
      }
    }
  }
}
</style>